package com.atguigu.orderservice.service.impl;

import com.atguigu.commonutils.ClientEntity.ClientCourse;
import com.atguigu.commonutils.ClientEntity.ClientMember;
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.orderservice.client.CourseClient;
import com.atguigu.orderservice.client.UserClient;
import com.atguigu.orderservice.entity.TOrder;
import com.atguigu.orderservice.mapper.TOrderMapper;
import com.atguigu.orderservice.service.TOrderService;
import com.atguigu.orderservice.utils.RedisIdWorker;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author huangqicai
 * @since 2023-03-31
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private CourseClient courseClient;

    @Autowired
    private RedisIdWorker redisIdWorker;

    /*根据课程id下订单，这里涉及到两个远程调用*/
    @Override
    public R saveOrder(String courseId, HttpServletRequest request) {
        /*1.获取用户信息 和 课程信息*/
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        ClientMember userInfo = userClient.getLoginInfo(userId);
        ClientCourse courseInfo = courseClient.getCourseInfoClient(courseId);
        /*2.创建订单*/
        TOrder tOrder = new TOrder();
        /*生成订单号*/
        String orderNo = String.valueOf(redisIdWorker.nextId("order"));
        tOrder.setOrderNo(orderNo);
        tOrder.setCourseId(courseInfo.getId());
        tOrder.setCourseTitle(courseInfo.getTitle());
        tOrder.setCourseCover(courseInfo.getCover());
        tOrder.setTeacherName(courseInfo.getTeacherName());
        tOrder.setMemberId(userInfo.getId());
        tOrder.setNickname(userInfo.getNickname());
        tOrder.setMobile(userInfo.getMobile());
        tOrder.setTotalFee(courseInfo.getPrice());
        tOrder.setStatus(0);/*表示订单没有支付*/
        baseMapper.insert(tOrder);
        return R.ok().data("orderId", tOrder.getOrderNo()).data("order", tOrder);
    }

    /*根据订单id获取订单信息*/
    @Override
    public R getOrderInfo(String orderNoId) {
        TOrder tOrder = baseMapper.selectOne(new QueryWrapper<TOrder>().eq("order_no", orderNoId));
        if(tOrder==null){
            return R.error().message("创建订单失败~");
        }
        return R.ok().data("item", tOrder);
    }

    /*根据用户id和课程id去查询订单信息*/
    @Override
    public boolean isBuyCourse(String memberId, String courseId) {
        Integer count = baseMapper.selectCount(new QueryWrapper<TOrder>().eq("member_id", memberId).eq("course_id", courseId));
        if(count>0){
            return true;
        }else {
            return false;
        }
    }

}
